const fs = require('fs');
const echarts = require('echarts');

// 参数验证
if (process.argv.length < 3) {
  console.error('参数数量错误！');
  process.exit(1);
}

const outputPath = process.argv[2];
const width = process.argv[3] || 600;   // 可选：图表宽度
const height = process.argv[4] || 400;  // 可选：图表高度

// 从标准输入读取配置
let inputData = '';
process.stdin.setEncoding('utf8');

process.stdin.on('data', chunk => {
  inputData += chunk;
});

process.stdin.on('end', () => {
  try {
    // 解析配置
    const option = new Function('return ' + inputData.trim())();

    // 创建图表实例
    const chart = echarts.init(null, null, {
      renderer: 'svg',
      ssr: true,
      width: Number(width),
      height: Number(height)
    });

    // 应用配置
    chart.setOption(option);

    // 生成SVG
    const svgStr = chart.renderToSVGString();

    // 写入文件
    fs.writeFile(outputPath, svgStr, err => {
      chart.dispose();

      if (err) {
        console.error(`错误：文件写入失败 (${err.message})`);
        process.exit(2);
      }

      console.log(`图表已成功生成至：${outputPath}`);
      console.log(`图表尺寸：${width}x${height}px`);
      process.exit(1); // 这里一定要返回1，会在java程序中有验证
    });

  } catch (e) {
    console.error('配置解析失败：', e.message);
    console.log('输入的配置内容：');
    console.log(inputData);
    process.exit(2);
  }
});

/*

echo "{animation:false,tooltip:{trigger:'axis',axisPointer:{type:'cross',label:{backgroundColor:'#6a7985'}}},legend:{data:['流入','流出']},grid:{left:'3%',right:'4%',bottom:'3%',containLabel:true},xAxis:[{type:'category',boundaryGap:false,data:['2025-04-05T00:00:00','2025-04-10T00:00:00','2025-04-15T00:00:00']}],yAxis:[{type:'value',name:'流入值'},{type:'value',name:'流出值'}],series:[{name:'流入',type:'line',stack:'Total',areaStyle:{color:'rgba(0,0,255,0.2)'},emphasis:{focus:'series'},yAxisIndex:0,lineStyle:{color:'rgba(0,0,255,0.4)'},data:[2.3128836E7,2.31288362E8,2312.0]},{name:'流出',type:'line',areaStyle:{color:'rgba(255,0,0,0.1)'},emphasis:{focus:'series'},yAxisIndex:1,lineStyle:{color:'rgba(255,0,0,0.4)'},data:[24707.0,2.470748705E9,2470.0]}]}
" | node genSVG.js ./chart.svg

*/
